<template>
  <view
    class="main-content pt-623px"
    :style="{ backgroundImage: `url(${ossImg('others/cloudsample/ld_bg2.png')})`,}"
  >
    <!--  规则及中奖记录   -->
    <view class="fixed-btn__group w-375px absolute top-23px right-0 flex justify-end mb-7px">
      <image
        class="w-78px h-26px"
        :src="ossImg('others/cloudsample/rule_btn.png')"
        @click.stop="onOpenDialog"
      ></image>
      <image
        class="w-78px h-26px mt-5px"
        :src="ossImg('others/cloudsample/record_btn.png')"
        @click.stop="viewPrizeRecord"
      ></image>
    </view>
    <!--  按钮组  -->
    <view class="flex mb-9px">
      <image
        class="w-137px h-47px mr-13px"
        :src="ossImg('others/cloudsample/ld_btn_2.png')"
        @click.stop="handleScanCode"
      ></image>
      <image
        class="w-137px h-47px"
        :src="ossImg('others/cloudsample/ld_btn_1.png')"
        @click.stop="goBuy"
      ></image>
    </view>
    <!--  Bottom Tips 2  -->
    <view class="text-line mb-8px">二维码无法识别？<text @click.stop="goToWriteOff">试试手动核销</text></view>
    <!--  Bottom Tips 1  -->
    <view class="text-line mb-34px" @click="onCheck">
      <image class="w-8px h-8px" :src="ossImg(`others/cloudsample/${state.agree ? 'check' : 'uncheck'}.png`)" />
      已阅读并同意<text @click.stop="onOpenDialog('rule')">活动规则</text>和<text @click.stop="onOpenDialog('privacy')">隐私声明</text>
    </view>
    <!--  规则/隐私弹窗  -->
    <content-dialog
      v-if="ruleModalVisible"
      :modalType="modalType"
      @close="ruleModalVisible = false"
      @service="handleService"
      @back="ruleModalVisible = false"
    ></content-dialog>
    <!--  去购买弹窗  -->
    <go-buy-dialog
      v-if="state.goBuyVisible"
      @close="handleCloseGoBuyModal"
      @offline="handleToOfflineStore"
      @online="handleOpenTaobaoDialog"
    ></go-buy-dialog>
    <!--  结果弹窗  -->
    <result-dialog
      v-if="state.resultDialogVisible"
      :result-code="state.resulCode"
      @close="state.resultDialogVisible = false"
    ></result-dialog>
    <!--  淘口令弹窗  -->
    <taobao-dialog
      v-if="state.tbDialogVisible"
      @close="state.tbDialogVisible = false"
    ></taobao-dialog>
    <!--  联系客服不同方式  -->
    <van-action-sheet
      :show="state.contactVisible"
      :actions="actions"
      cancel-text="取消"
      @select="onAction"
      @cancel="onActionCancel"
    />
    <!--  门店列表  -->
    <store-modal
      v-if="state.storeDialogVisible"
      @close="state.storeDialogVisible = false"
    ></store-modal>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue"
import { generateSign2, ossImg, ObjectToQueryString, message } from "@/utils/utils";
import { onHide, onLoad, onUnload, onShow } from "@dcloudio/uni-app";
import { userLogin } from "@/services/utils";
import { onShareAppMessage } from "@dcloudio/uni-app"
import { QRCODE_BASE_URI, ShareConfig } from "./config";
import GoBuyDialog from "./components/GoBuyDialog.vue";
import ResultDialog from "./components/ResultDialog.vue";
import ContentDialog from "./components/contentDialog.vue";
import StoreModal from "@/campaign/pages/cloudsample/components/StoreModal.vue";
import TaobaoDialog from "@/campaign/pages/cloudsample/components/TaobaoDialog.vue";

const actions = [
  { name: '4000880325', color: '#0f40de' },
  { name: '联系客服', openType: 'contact' },
]
const locationInfo = ref({ latitude: "", longitude: "" });
const emdlz = getApp().emdlz2
const modalType = ref('rule') // privacy
const ruleModalVisible = ref(false)
const state = reactive({
  loading: true,
  goBuyVisible: false,
  contactVisible: false,
  resultDialogVisible: false,
  storeDialogVisible: false,
  tbDialogVisible: false,
  resulCode: 0,
  qrcodeUrl: '',
  agree: uni.getStorageSync('CLOUD_SAMPLE_AGREE'),
  needRetry: false
})

let enterTime = "";
let outTime = "";
let stayTime = "";

onLoad((options) => {
  if (options.q) state.qrcodeUrl = decodeURIComponent(decodeURIComponent(options.q))
  getApp().accessLogAdd();
  if (options.isList) {
    setTimeout(() => {
      state.storeDialogVisible = true
    }, 50)
  }
})

onShow(async () => {
  // 用户进入时间
  enterTime = new Date();

  if (!getApp().globalData.user.phone) return

  if (state.needRetry) {
    setTimeout(() => {
      if (state.qrcodeUrl) handleUrlCodeSubmit(state.qrcodeUrl)
      state.needRetry = false
    }, 100)
  }
})

const afterPhoneValidate = () => {
  return new Promise((resolve, reject) => {
    const currentPage = getCurrentPages().at(-1)
    if (currentPage.route !== 'campaign/pages/cloudsample/index' || state.loading) return

    if (!getApp().globalData.user.phone) {
      uni.navigateTo({ url: "/pages/vip/register?tag=scanCode" });
      reject()
    }

    resolve()
  })
}

onMounted(async () => {
  state.loading = false
  // const started = new Date() > new Date('2024/04/01 00:00:00 ')
  // if (!started) {
  //   console.log('活动还没有开始')
  //   setTimeout(() => {
  //     uni.redirectTo({
  //       url: '/campaign/pages/cloudsample/status?status=0'
  //     })
  //   }, 200)
  //   return
  // }
  const ended = new Date() > new Date('2025/04/01 00:00:00')
  if (ended) {
    // 活动已结束
    setTimeout(() => {
      uni.redirectTo({
        url: '/campaign/pages/cloudsample/status?status=1'
      })
    }, 200)
  }

  await getApp().getUserInfo()

  const currentPage = getCurrentPages().at(-1)
  if (currentPage.route !== 'campaign/pages/cloudsample/index') return
  // 是否登录注册
  if (!getApp().globalData.user.phone) {
    if (state.qrcodeUrl) state.needRetry = true
    uni.navigateTo({ url: "/pages/vip/register?tag=scanCode" });
    return;
  }
  setTimeout(() => {
    if (state.qrcodeUrl) handleUrlCodeSubmit(state.qrcodeUrl)
  }, 100)
})

const handleOpenTaobaoDialog = () => {
  state.goBuyVisible = false
  state.tbDialogVisible = true
}

const handleToOfflineStore = () => {
  state.goBuyVisible = false
  setTimeout(() => {
    state.storeDialogVisible = true
  }, 50)
}
const uploadStayTimeEvent = (evt) => {
  console.log('---------stayTimeEvt', evt)
  if (!enterTime) return
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  console.log('----------stayTime', stayTime)
  emdlz('track','event','Oreo_eggy_landing_page','view','eggy_landing_page', stayTime);
}

onUnload(() => uploadStayTimeEvent('onBeforeMount'))
onHide(() => uploadStayTimeEvent('hide'))

onShareAppMessage(() => ShareConfig())

// 关闭去购买弹窗
const handleCloseGoBuyModal = () => {
  state.goBuyVisible = false
}

const onActionCancel = () => {
  console.log(modalType.value)
  if (modalType.value === 'rule') {
    // 事件追踪-20
    emdlz('track','event','Oreo_eggy_rules_page','click','cancel_cs','');
  }
  if (modalType.value === 'privacy') {
    // 事件追踪-26
    console.log('隐私取消')
    emdlz('track','event','Oreo_eggy_policy_page','click','cancel_cs1','');
  }
  state.contactVisible = false
}

// 联系客服菜单点击
const onAction = e => {
  // 在线客服
  if (e.detail.openType === 'contact') {
    if (modalType.value === 'rule') {
      // 事件追踪-19
      emdlz('track','event','Oreo_eggy_rules_page','click','contect_cs','');
    }
    if (modalType.value === 'privacy') {
      // 事件追踪-25
      emdlz('track','event','Oreo_eggy_policy_page','click','contect_cs1','');
    }
    return
  }
  // 点击400电话
  if (modalType.value === 'rule') {
    // 事件追踪-18
    emdlz('track','event','Oreo_eggy_rules_page','click','call_cs','');
  }
  if (modalType.value === 'privacy') {
    // 事件追踪-24
    emdlz('track','event','Oreo_eggy_policy_page','click','call_cs1','');
  }
  uni.makePhoneCall({
    phoneNumber: actions?.[0]?.name //仅为示例
  });
}

// 点击联系客服
const handleService = () => {
  if (modalType.value === 'rule') {
    // 事件追踪-17
    emdlz('track','event','Oreo_eggy_rules_page','click','click_cs','');
  }
  if (modalType.value === 'privacy') {
    // 事件追踪-23
    emdlz('track','event','Oreo_eggy_policy_page','click','click_cs1','');
  }
  state.contactVisible = true
}

// 点击勾选框
const onCheck = () => {
  state.agree = !state.agree
  uni.setStorageSync('CLOUD_SAMPLE_AGREE', state.agree)
  emdlz('track','event','Oreo_eggy_landing_page','click','agree_poliy_rules','');
}

// 点击中奖记录
const viewPrizeRecord = async () => {
  emdlz('track','event','Oreo_eggy_landing_page','click','prize_records','');
  if (!state.agree) return message("请先同意相关协议!");
  await afterPhoneValidate()
  linkTo(`/campaign/pages/cloudsample/webview?${getWebviewSearchParams({})}&source=record`);
}

// 点击手动核销
const goToWriteOff = () => {
  emdlz('track','event','Oreo_eggy_landing_page','click','add_code','');
  if (!state.agree) return message("请先同意相关协议!");
  linkTo('/campaign/pages/cloudsample/verification')
}

const goBuy = () => {
  emdlz('track','event','Oreo_eggy_landing_page','click','go_purchase','');
  state.goBuyVisible = true
}

const onOpenDialog = t => {
  modalType.value = typeof t === 'string' ? t : 'rule'
  if (modalType.value === 'rule') {
    if (typeof t === 'string') {
      // 点击活动规则
      emdlz('track','event','Oreo_eggy_landing_page','click','check_rules1','');
    } else {
      // 点击右上角活动规则
      emdlz('track','event','Oreo_eggy_landing_page','click','check_rules','');
    }
  } else {
    // 点击隐私声明
    emdlz('track','event','Oreo_eggy_landing_page','click','view_policy','');
  }
  ruleModalVisible.value = true
}

const linkTo = url => uni.navigateTo({ url })

// 生成兑奖H5需要参数
const getWebviewSearchParams = (body) => ObjectToQueryString({
  // 'accesstoken': uni.getStorageSync("TOKEN"),
  'code': body.qrCode || '',
  // 'openid': uni.getStorageSync("OPENID"),
  // 'unionid': uni.getStorageSync("UNIONID"),
  // 'memberid': body?.memberScore?.memberId || getApp().globalData?.user?.memberScore?.memberId || '',
  // 'agree': 'true'
})

/**
 * 一物一码校验
 * @param url 完整奖品链接
 * @returns {Promise<void>}
 */
const handleUrlCodeSubmit = (url) => {
  // uni.getLocation({
  //   type: "gcj02",
  //   success(res) {
  //     locationInfo.value.latitude = res.latitude;
  //     locationInfo.value.longitude = res.longitude;
  //   },
  //   complete: async () => {
  //     const body = {
  //       userValue: uni.getStorageSync("OPENID"),
  //       qrCode: url.split('/').at(-1),
  //       source: "Q4",
  //       timestamp: Date.parse(new Date()),
  //       lng: locationInfo.value.longitude,
  //       lat: locationInfo.value.latitude,
  //     }
  //     // 域名判断不对处理
  //     const hostnameArr = QRCODE_BASE_URI.split('.')
  //     hostnameArr.shift()
  //     if (url.includes(hostnameArr.join('.')) && !url.includes(QRCODE_BASE_URI)) {
  //       state.resulCode = 'err'
  //       state.resultDialogVisible = true
  //       return
  //     }
  //     // 没有获取到OPENID
  //     if (!body.userValue) {
  //       try {
  //         await getApp().getUserLoginInfo()
  //         const user = await getApp().getUserInfo()
  //         linkTo(`/campaign/pages/cloudsample/webview?${getWebviewSearchParams({ ...body, ...user })}`);
  //       } catch (e) {
  //         uni.showToast({ title: '服务器响应错误', icon: 'none' })
  //       }
  //       return
  //     }
  //     uni.request({
  //       url: `${QRCODE_BASE_URI}/zex-qr/api/qr/validation`,
  //       method: "get",
  //       data: {
  //         ...body,
  //         ...{ sign: generateSign2(body) },
  //       },
  //       success: (result) => {
  //         // 码正确处理
  //         if (result.data.code === 200) {
  //           // 静默拿取微信用户的 openId 与 unionId 信息
  //           uni.login({
  //             provider: "weixin",
  //             success: async (loginResult) => {
  //               const loginParam = { type: 1, code: loginResult.code };
  //               const { data } = await userLogin(loginParam);
  //               uni.setStorageSync("TOKEN", data?.accessToken);
  //               uni.setStorageSync("OPENID", data?.openId);
  //               uni.setStorageSync("UNIONID", data?.unionId);
  //               getApp().emdlz2("set", "user", "openid", data?.openId);
  //               getApp().emdlz2("set", "user", "unionId", data?.unionId);
  //               // 兑奖H5
  //               linkTo(`/campaign/pages/cloudsample/webview?${getWebviewSearchParams(body)}`);
  //             },
  //           });
  //           return
  //         }
  //         // 接口报错
  //         if (!result?.data.code) return linkTo(`/campaign/pages/cloudsample/status?status=2`);
  //         // 码错误处理
  //         state.resulCode = result?.data?.code || 'err'
  //         state.resultDialogVisible = true
  //       },
  //       fail: requestErr => {
  //         uni.showToast({
  //           title: requestErr.data.message,
  //           icon: "none",
  //           duration: 2000,
  //         });
  //       }
  //     })
  //   }
  // })
  return linkTo(`/campaign/pages/cloudsample/status?status=1`)
}

const handleScanCode = async () => {
  emdlz('track','event','Oreo_eggy_landing_page','click','go_scan','');
  if (!state.agree) return message("请先同意相关协议!");
  await afterPhoneValidate()
  uni.scanCode({
    success: ({ result }) => handleUrlCodeSubmit(result)
  })
}

const handleBackHome = () => {
  getApp().emdlz2('track','event','oreo_cake_onepack_landing_page','click','back_universe_times','');
  setTimeout(() => {
    uni.switchTab({ url: "/pages/home/home" })
  }, 300)
}
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

image {
  display: block;
}

.main-content {
  width: 100%;
  min-height: 100vh;
  background-color: #0CB2FD;
  background-position: top left;
  background-size: 375px 748px;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}
.fixed-btn__group {
  flex-direction: column;
  align-items: flex-end;
  .fixed-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-bottom: 14px;
    text {
      color: white;
      font-size: 9px;
      margin-top: 3px;
      line-height: 1;
    }
  }
}
.text-line {
  color: #08134F;
  display: flex;
  align-items: center;
  font-size: 10px;
  font-weight: 500;
  line-height: 1;
  & > image {
    margin-right: 6px;
  }
  text {
    text-decoration: underline;
  }
}
</style>
